package com.yanggu.payment.config;

import com.yanggu.payment.feign.weixin_pay.WeiXinPayIgnoreValidaResponse;
import feign.Client;
import feign.httpclient.ApacheHttpClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.HttpClient;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;

import java.lang.reflect.Method;

/**
 * @version V1.0
 * @author: YangGu
 * @date: 2022/5/5 16:01
 * @description: 微信支付Feign的配置类
 */
@Slf4j
public class WeiXinPayFeignConfig {

    /**
     * 这个bean的作用是。将feign的请求地址换成httpclient。 然后自己提供wxPayClient。
     * wxPayClient自动处理了请求签名和响应验签
     * wxPayClientWithNoValidaResponse 处理请求签名, 但是不处理响应验签
     *
     * @param httpClient client
     * @return client
     */
    @Bean(name = "weiXinPayFeignClient")
    public Client feignClient(@Qualifier("wxPayClient") HttpClient httpClient,
                              @Qualifier("wxPayClientWithNoValidaResponse") HttpClient httpClientWithNoValidaResponse) {
        //处理请求签名和响应验签的client
        ApacheHttpClient apacheHttpClient = new ApacheHttpClient(httpClient);
        //处理请求签名, 不进行响应签名的校验
        ApacheHttpClient apacheHttpClientWithNoValidaResponse = new ApacheHttpClient(httpClientWithNoValidaResponse);
        return (request, options) -> {
            //获取feign接口中的方法对应的method对象
            Method method = request.requestTemplate().methodMetadata().method();
            //如果注解存在, 则不进行响应验签
            if (method.isAnnotationPresent(WeiXinPayIgnoreValidaResponse.class)) {
                return apacheHttpClientWithNoValidaResponse.execute(request, options);
            } else {
                //如果注解不存在, 需要进行响应验签
                return apacheHttpClient.execute(request, options);
            }
        };
    }

}
